package com.ssy.lingxi.member.merchant.serviceimpl.base;

import com.ssy.lingxi.common.constant.basic.EnableDisableStatus;
import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.member.merchant.entity.MemberQualityDO;
import com.ssy.lingxi.member.merchant.entity.MemberRelationDO;
import com.ssy.lingxi.member.merchant.model.vo.validate.request.MemberQualityVO;
import com.ssy.lingxi.member.merchant.model.vo.validate.response.MemberQualityQueryVO;
import com.ssy.lingxi.member.merchant.repository.MemberQualityRepository;
import com.ssy.lingxi.member.merchant.service.base.IBaseMemberQualificationService;
import com.ssy.lingxi.member.merchant.utils.SecurityStringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 会员资质（文件）基础服务接口
 * @author 万宁
 * @version 2.0.0
 * @date 2021-05-22
 */
@Service
public class BaseMemberQualificationServiceImpl implements IBaseMemberQualificationService {
    @Resource
    private MemberQualityRepository memberQualityRepository;

    /**
     * 检查会员资质，并更新relationDo关联的MemberQualityDO中的信息（已保存，调用方需要保存relationDO）
     *
     * @param relationDO  会员关系
     * @param qualityList 资质文件列表
     * @return 检查结果
     */
    @Transactional(rollbackFor = BusinessException.class)
    @Override
    public Wrapper<Void> checkAndSaveMemberQualities(MemberRelationDO relationDO, List<MemberQualityVO> qualityList) {
        if(!CollectionUtils.isEmpty(relationDO.getQualities())) {
            relationDO.getQualities().clear();
        }
        relationDO.setQualities(new HashSet<>());
        memberQualityRepository.deleteByRelation(relationDO);

        if(CollectionUtils.isEmpty(qualityList)) {
            return Wrapper.success();
        }

        //检查资质文件日期格式
        if(qualityList.stream().filter(memberQualityVO -> memberQualityVO.getPermanent().equals(EnableDisableStatus.DISABLE.getCode())).anyMatch(memberQualityVO -> SecurityStringUtils.notDateString(memberQualityVO.getExpireDay()))) {
            return Wrapper.fail(ResponseCode.MC_MS_QUALITY_FILE_DATE_FORMAT_ERROR);
        }

        List<MemberQualityDO> qualities = qualityList.stream().map(quality -> {
            MemberQualityDO qualityDO = new MemberQualityDO();
            qualityDO.setRelation(relationDO);
            qualityDO.setUrl(quality.getUrl());
            qualityDO.setName(quality.getName());
            qualityDO.setPermanent(quality.getPermanent());
            if(quality.getPermanent().equals(EnableDisableStatus.ENABLE.getCode())) {
                qualityDO.setExpireTime(LocalDateTime.now());
            } else {
                qualityDO.setExpireTime(LocalDateTime.parse(quality.getExpireDay().concat(" 00:00:00"), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            }
            return qualityDO;
        }).collect(Collectors.toList());

        memberQualityRepository.saveAll(qualities);
        relationDO.setQualities(new HashSet<>(qualities));

        return Wrapper.success();
    }

    /**
     * 检查会员资质，调用方要设置MemberRelationDO并保存
     *
     * @param qualityList 资质文件接口参数列表
     * @return 资质文件
     */
    @Override
    public Wrapper<List<MemberQualityDO>> checkMemberQualities(List<MemberQualityVO> qualityList) {
        if(CollectionUtils.isEmpty(qualityList)) {
            return Wrapper.success(new ArrayList<>());
        }

        //检查资质文件日期格式
        if(qualityList.stream().filter(memberQualityVO -> memberQualityVO.getPermanent().equals(EnableDisableStatus.DISABLE.getCode())).anyMatch(memberQualityVO -> SecurityStringUtils.notDateString(memberQualityVO.getExpireDay()))) {
            return Wrapper.fail(ResponseCode.MC_MS_QUALITY_FILE_DATE_FORMAT_ERROR);
        }

        return Wrapper.success(qualityList.stream().map(quality -> {
            MemberQualityDO qualityDO = new MemberQualityDO();
            qualityDO.setUrl(quality.getUrl());
            qualityDO.setName(quality.getName());
            qualityDO.setPermanent(quality.getPermanent());
            if(quality.getPermanent().equals(EnableDisableStatus.ENABLE.getCode())) {
                qualityDO.setExpireTime(LocalDateTime.now());
            } else {
                qualityDO.setExpireTime(LocalDateTime.parse(quality.getExpireDay().concat(" 00:00:00"), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            }
            return qualityDO;
        }).collect(Collectors.toList()));
    }

    /**
     * 查询会员资质列表
     *
     * @param relationDO 会员关系
     * @return 查询结果
     */
    @Override
    public List<MemberQualityQueryVO> findMemberQualities(MemberRelationDO relationDO) {
        return memberQualityRepository.findByRelation(relationDO).stream().map(memberQualityDO -> {
            MemberQualityQueryVO queryVO = new MemberQualityQueryVO();
            queryVO.setUrl(memberQualityDO.getUrl());
            queryVO.setName(memberQualityDO.getName());
            queryVO.setPermanent(memberQualityDO.getPermanent());
            queryVO.setExpireDay(memberQualityDO.getPermanent().equals(EnableDisableStatus.ENABLE.getCode()) ? "" : memberQualityDO.getExpireTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
            return queryVO;
        }).collect(Collectors.toList());
    }
}
